/*
 * @Author: Wangjun
 * @Date: 2022-01-13 14:26:23
 * @LastEditTime: 2023-12-16 16:21:16
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \xr_node_calc\controllers\api.go
 * hnxr
 */
package controllers

import (
	//"encoding/json"
	"io"
	"net/http"
	"os"
	"strings"

	"gitee.com/haodreams/golib/autoroute/controller"
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/op_node/models"
	jsoniter "github.com/json-iterator/go"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

// ApiController 表相关的操作
type ApiController struct {
	controller.Controller
}

/**
 * @description: 发布画布
 * @return {*}
 */
func (m *ApiController) Release() {
	data, err := io.ReadAll(m.Request.Body)
	if err != nil {
		logs.Warn(err.Error())
		m.Error(err.Error())
		return
	}
	m.Request.Body.Close()
	err = models.Release(data)
	if err != nil {
		m.Error(err.Error())
		return
	}
	m.Msg("发布成功")
}

func (m *ApiController) Nodes() {
	data, err := os.ReadFile("data/nodes.json")
	if err != nil {
		logs.Warn(err.Error())
		m.Error(err.Error())
		return
	}
	m.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
	_, err = m.Writer.Write(data)
	if err != nil {
		logs.Warn(err.Error())
	}
}

/**
 * @description: 保存画布
 * @return {*}
 */
func (m *ApiController) Save() {
	data, err := io.ReadAll(m.Request.Body)
	if err != nil {
		logs.Warn(err.Error())
		m.Error(err.Error())
		return
	}
	m.Request.Body.Close()
	var mp map[string]any
	err = json.Unmarshal(data, &mp) //m.BindJSON(&mp)
	if err != nil {
		logs.Warn(err.Error())
		m.Error(err.Error())
		return
	}
	fileName := mp["filename"]
	name, ok := fileName.(string)
	if ok {
		if name == "" {
			m.Error("保存失败, 文件名不能为空")
			return
		}
		if !strings.HasSuffix(name, ".json") {
			name += ".json"
		}
		data, err := json.Marshal(mp)
		if err != nil {
			m.Error("保存失败, " + err.Error())
			return
		}
		err = os.WriteFile("data/nodes/"+name, data, 0755)
		if err != nil {
			m.Error("保存失败, " + err.Error())
			return
		}
		m.Msg("保存成功")
		return
	}
	m.Error("保存失败, 需要给出文件名参数")
}

// 读取文件
func (m *ApiController) File() {
	path := "data/nodes/" + m.GetParam().GetString("path")
	data, err := os.ReadFile(path)
	if err != nil {
		var er error
		path = "data/run/" + m.GetParam().GetString("path")
		data, er = os.ReadFile(path)
		if er != nil {
			m.Error(err.Error())
			return
		}
	}
	m.Data(string(data))
}

// Tree 标签
type Tree struct {
	ID       string  `json:"id"`
	Label    string  `json:"label"`
	Icon     string  `json:"icon"`
	Children []*Tree `json:"children"`
}

// List 列出所有文件
func (m *ApiController) List() {
	path := "data/nodes/" + m.GetParam().GetString("path")
	fi, err := os.ReadDir(path)
	if err != nil {
		m.Error(err.Error())
		return
	}
	ifs := make([]*Tree, 0, len(fi))
	for _, f := range fi {
		if f.IsDir() {
			continue
		}
		inf := new(Tree)
		inf.Label = f.Name()
		inf.ID = f.Name()
		ifs = append(ifs, inf)
	}
	m.JSON(http.StatusOK, ifs)
}

// http://127.0.0.1:8080/static/node/#/view?path=pvbox.json&category=pv_box&devid=2
func (m *ApiController) ParamsData() {
	params := m.GetParam()
	devid, _ := params.GetInt("devid")
	data, err := models.GetBoss().GetTaskData(params.GetString("path"), params.GetString("category"), devid)
	if err != nil {
		m.Error(err.Error())
		return
	}
	m.Data(data)
}

/**
 * @description: 重新加载基础数据
 * @return {*}
 */
func (m *ApiController) ReloadData() {
	//models.GetBoss().ReloadData()
	m.Msg("OK")
}
